import Request from 'luch-request'; //npm下载引入luch-request

const http = new Request({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 30000,
  header: {
    'Content-Type': 'application/json;charset=UTF-8;'
  },
});

//请求拦截器
http.interceptors.request.use(
  (config) => {
    // 显示加载动画
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
    // 如果token存在，并且不是登录接口，则添加Authorization头
    if (uni.getStorageSync('token') && config.url?.toLocaleLowerCase().includes('/api/_account/loginjwt') == false) {
      config.header!['Authorization'] = 'Bearer ' + uni.getStorageSync('token');
    }
    return config;
  },
  (error) => {
    uni.hideLoading();
    return Promise.reject(error);
  },
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    // 隐藏加载动画
    uni.hideLoading();
    // 如果响应头有content-disposition，则将contentDisposition赋值给response.data
    if (response.header!['content-disposition']) {
      response.data.contentDisposition = response.header!['content-disposition'];
    }
    // 返回响应数据
    return response.data;
  },
  (error) => {
    uni.hideLoading();
    if (error.statusCode === 400) {
      if (typeof error.data === 'string') {
        uni.showToast({
          title: error.data,
          duration: 2000,
          icon: "none",
        });
      } else {
        if (error.data.Message && error.data.Message.constructor == Array && error.data.Message.length > 0) {
          uni.showToast({
            title: error.data.Message[0],
            duration: 2000,
            icon: "none",
          });
        } else if (error.data.Form && Object.getOwnPropertyNames(error.data.Form).length > 0) {
          uni.showToast({
            title: error.data.Form[Object.getOwnPropertyNames(error.data.Form)[0]],
            duration: 2000,
            icon: "none",
          });
        }
      }
    } else if (error.statusCode === 401 || error.statusCode === 4001) {
      uni.showToast({
        title: '登录已过期，请重新登录',
        duration: 2000,
        icon: "none",
      });
    } else if (error.statusCode === 403) {
      uni.showToast({
        title: '无权限',
        duration: 2000,
        icon: "none",
      });
      // 跳转到工作台
      uni.reLaunch({
        url: '/pages/work/work',
      });
    } else {
      if (error.data) uni.showToast({
        title: error.data,
        duration: 2000,
        icon: "none",
      });
    }
    return Promise.reject(error);
  },
);

export default http;

// 图片上传功能
export const uploadImage = async (
  filePath: string,
  name: string = 'file'
): Promise<string> => {
  return new Promise((resolve, reject) => {
    // 显示上传进度
    uni.showLoading({
      title: '上传中...',
      mask: true
    });
    // 获取token
    const token = uni.getStorageSync('token');
    const headers: Record<string, string> = {};
    if (token) {
      headers['Authorization'] = 'Bearer ' + token;
    }
    uni.uploadFile({
      url: import.meta.env.VITE_BASE_URL + "/api/_file/upload",
      filePath: filePath,
      name: name,
      header: headers,
      success: (res) => {
        uni.hideLoading();
        const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
        resolve(data.Id || '');
      },
      fail: (err) => {
        uni.hideLoading();
        console.error('上传失败：', err);
        reject(err);
      },
    });
  });
};